<template>
  <div class="fillcontain" style="padding: 25px 15px 15px;">
    <div style="display:flex; height: auto;">
      <exam-project-library-list ref="examProjectLibrary" @queryTableData="queryTableData" :manual="true"></exam-project-library-list>

      <!-- 右侧表格 -->
      <div class="rightBox">
        <div class="right-title">{{ tableTitle ? `${tableTitle}-项目信息` : '项目信息' }}</div>

        <div style="margin:35px 0px 0px 20px ;">
          <!-- headStyle表头内容居中方法  rowStyle表格内容居中方法  -->
          <el-table ref="multiTable" :data="relationList"  style="width: 100%;" height="calc(100vh - 340px)">
            <el-table-column label="是否显示" width="80" align="center">
              <template slot-scope="scope">
                <!-- `checked` 为 true显示 或 false不显示 -->
                <el-checkbox v-model="scope.row.isShow" true-label="1" false-label="0" :disabled="currentRow.isLock"></el-checkbox>
              </template>
            </el-table-column>

            <el-table-column label="子项目名称" width="115" show-overflow-tooltip align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.projectName }}</span>
              </template>
            </el-table-column>

            <el-table-column label="别称" width="250" class-name="col-reset">
              <template slot-scope="scope">
                <span class="synonym-item" v-for="(tag, index) in scope.row.anotherConfigList" :key="index">{{tag.anotherName}} <i style="cursor: pointer;" class="el-icon-close" v-if="!currentRow.isLock" @click="delTag(scope.row.anotherConfigList, index)"></i></span>
                <span class="synonym-item" style="border:1px dashed #dcdfe6;cursor: pointer;" @click="addNewAlias(scope.$index)" v-if="!currentRow.isLock"><i class="el-icon-plus"></i></span>
              </template>
            </el-table-column>

            <el-table-column label="英文缩写" width="105" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.abbreviation" placeholder="请输入" style="width:95px;" :disabled="currentRow.isLock" :maxlength="50" @input="inputChange($event,scope.row,'abbreviation')">
                </el-input>
              </template>
            </el-table-column>

            <el-table-column label="参考区间" width="250" class-name="col-reset">
							<template slot-scope="scope">
                <span class="synonym-item" v-for="(tag, index) in scope.row.intervalConfigList" :key="index">{{ tag.type=='1' ? `${tag.referenceIntervalFirst}-${tag.referenceIntervalSecond}` : tag.referenceIntervalFirst}} <i style="cursor: pointer;" class="el-icon-close" v-if="!currentRow.isLock" @click="delTag(scope.row.intervalConfigList, index)"></i></span>
                <span class="synonym-item" style="border:1px dashed #dcdfe6;cursor: pointer;" @click="addNewRange(scope.$index)" v-if="!currentRow.isLock"><i class="el-icon-plus"></i></span>
              </template>
            </el-table-column>
            <el-table-column label="单位" width="200" class-name="col-reset">
              <template slot-scope="scope">
                <span class="synonym-item" v-for="(tag, index) in scope.row.unitConfigList" :key="index" :style="`background:${tag.isdefault == '1' ? '#81d3f8' : '#f5f5f5'}`">{{tag.unit}} <i style="cursor: pointer;" class="el-icon-close" v-if="!currentRow.isLock" @click="delTag(scope.row.unitConfigList, index)"></i></span>
                <span class="synonym-item" style="border:1px dashed #dcdfe6;cursor: pointer;" @click="addNewUnic(scope.$index)" v-if="!currentRow.isLock"><i class="el-icon-plus"></i></span>
              </template>
            </el-table-column>
          </el-table>
        </div>
				<div style="text-align:center; margin: 16px 0;">
					<el-button class="Defaultbutton" @click="savePage" :disabled="currentRow.isLock">保存</el-button>
				</div>
      </div>
    </div>
		<!-- 弹窗 -->
		<el-dialog :visible.sync="addAlias" width="520px" v-if="addAlias" center title="新增别称" :close-on-click-modal="false">
			<!--需要弹出的内容部分-->
			<el-form :model="dislogAliasData" label-width="80px" ref="dislogAliasData" :rules="aliasRules">
				<el-row>
					<el-col :span="24">
						<el-form-item label="别称" prop="newAlias">
							<el-input v-model="dislogAliasData.newAlias" :maxlength="50"></el-input>
						</el-form-item>
					</el-col>
				</el-row>	
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="addAlias = false">取 消</el-button>
				<el-button class="Defaultbutton" @click="saveAlias">保存</el-button>
			</span>
		</el-dialog>
		<!-- 弹窗 -->
		<el-dialog :visible.sync="addUnic" width="520px" v-if="addUnic" center title="新增单位" :close-on-click-modal="false">
			<!--需要弹出的内容部分-->
			<el-form :model="dislogUnicData" label-width="80px" ref="dislogUnicData" :rules="unicRules">
				<el-row>
					<el-col :span="24">
						<el-form-item label="单位" prop="newUnic">
							<el-input v-model="dislogUnicData.newUnic"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="是否默认" prop="isdefault">
							<el-switch v-model="dislogUnicData.isdefault"></el-switch>
						</el-form-item>
					</el-col>
				</el-row>	
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="addUnic = false">取 消</el-button>
				<el-button class="Defaultbutton" @click="saveUnic">保存</el-button>
			</span>
		</el-dialog>
		<!-- 弹窗 -->
		<el-dialog :visible.sync="addRange" v-if="addRange" width="800px" center title="参考区间" :close-on-click-modal="false">
			<!--需要弹出的内容部分-->
			<el-form :model="dislogRangeData" label-width="100px" ref="dislogRange" :rules="rangeRules">
				<el-row>
					<el-col :span="12">
						<el-form-item label="性别" prop="sex">
							<el-select clearable v-model="dislogRangeData.sex" filterable placeholder="">
								<el-option v-for="item in sexOptions" :key="item.id" :label="item.dictValue"
                  :value="item.id"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item :span="12" label="年龄" prop="age">
							<el-input v-model="dislogRangeData.age"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="体检机构" prop="physicalExaminationOrgCode">
							<el-select clearable v-model="dislogRangeData.physicalExaminationOrgCode" filterable placeholder="">
								<el-option v-for="item in companyOptions" :key="item.id" :label="item.dictValue"
                  :value="item.id"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12" v-if="false">
						<el-form-item label="体检机构" prop="physicalExaminationOrgName">
							<el-input v-model="dislogRangeData.physicalExaminationOrgName"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="生理分期" prop="physiologicalStaging">
							<el-select clearable v-model="dislogRangeData.physiologicalStaging" filterable placeholder="">
								<el-option v-for="item in phystageOptions" :key="item.id" :label="item.dictValue"
                  :value="item.id"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="分类"  style="height: 30px;" prop="type">
						<!-- <el-form-item> -->
							<el-radio-group v-model="dislogRangeData.type" @input="changeRangeType">
								<el-radio label="1">按区间段</el-radio>
								<el-radio label="2">按内容</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :span="7" v-show="dislogRangeData.type == '1'">
						<el-form-item label="参考区间" prop="referenceIntervalFirst">
							<el-input v-model="dislogRangeData.referenceIntervalFirst" :disabled="dislogRangeData.type == '2'"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="5" v-show="dislogRangeData.type == '1'">
						<el-form-item label="~" prop="referenceIntervalSecond" label-width="30px">
							<el-input v-model="dislogRangeData.referenceIntervalSecond" :disabled="dislogRangeData.type == '2'"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12" v-show="dislogRangeData.type != '1'">
						<el-form-item label="参考区间" prop="referenceIntervalFirst">
							<el-input v-model="dislogRangeData.referenceIntervalFirst" :disabled="dislogRangeData.type == '1'"></el-input>
						</el-form-item>
					</el-col>
					<!-- <el-col :span="12">
						<el-button
							type="danger"
							size="mini"
							style="margin-left: 100px;"
							plain
							icon="el-icon-circle-plus-outline"
							@click="addRangeItem"
							>新增
						</el-button>
					</el-col> -->
					
				</el-row>	
			</el-form>
			<el-button
				type="danger"
				size="mini"
				style="margin-left: 20px;"
				plain
				icon="el-icon-circle-plus-outline"
				@click="addRangeItem"
				>新增
			</el-button>
			<div style="height: 48px; line-height: 48px;">
				<span style="padding-left: 16px; border-left: 4px solid #f76767;">已定义信息</span>
			</div>
			<el-table ref="multipleTable" :data="dislogRangeTable"  style="width: 100%;border: 1px solid #e9e9e9;" >
				<el-table-column type="index" width="70" label="序号" align="center"> </el-table-column>
				<el-table-column label="性别" width="90" align="center">
					<template slot-scope="scope">
						<span>{{ scope.row.sex | formatDict(sexOptions)}}</span>
					</template>
				</el-table-column>
				<el-table-column label="年龄" width="90" align="center">
					<template slot-scope="scope">
						<span>{{ scope.row.age }}</span>
					</template>
				</el-table-column>
        <el-table-column label="体检机构" width="100" align="center" show-overflow-tooltip>
					<template slot-scope="scope">
						<span>{{ scope.row.physicalExaminationOrgName }}</span>
					</template>
				</el-table-column>
				<el-table-column label="生理分期" min-width="100" align="center" show-overflow-tooltip>
					<template slot-scope="scope">
						<span>{{ scope.row.physiologicalStaging | formatDict(phystageOptions) }}</span>
					</template>
				</el-table-column>
				<el-table-column label="参考区间" min-width="100" align="center" show-overflow-tooltip>
					<template slot-scope="scope">
						<span v-if="scope.row.type == '1'">{{ scope.row.referenceIntervalFirst }} ~ {{ scope.row.referenceIntervalSecond }}</span>
						<span v-if="scope.row.type == '2'">{{ scope.row.referenceIntervalFirst }} </span>
					</template>
				</el-table-column>

				<el-table-column label="操作" width="100" align="center">
					<template slot-scope="scope">
						<i class="el-icon-delete" style="color:#409EFF ; cursor: pointer;" @click="delRangeItem(scope.$index)"></i>
					</template>
				</el-table-column>
			</el-table>
			<span slot="footer" class="dialog-footer">
				<el-button @click="addRange = false">取 消</el-button>
				<el-button class="Defaultbutton" @click="saveRange">保存</el-button>
			</span>
		</el-dialog>
  </div>
</template>

<script>
import { getProjectInfo, saveReferenceIntervalInfo  } from '@/api/setting/maintain/extractMaintain.js'
import constant from '@/utils/constant';

import mixins from '@/utils/mixins'

import examProjectLibraryList from '../../../../common/examProjectLibraryList.vue'

import {
		getCodeDictProject,
	} from "@/api/taskCenter/enterWorkPool";

export default {
	mixins: [mixins],
	components: {
    examProjectLibraryList,
  },
  data() {
		var checkInterval = (rule, value, callback) => {
      let reg = /^(-)?[0-9]+([.][0-9]{0,})?$/
			if (this.dislogRangeData.type == '1' && !value) {
				return callback(new Error('请输入参考区间'));
			}else if(this.dislogRangeData.type == '1' && value && !value.match(reg) && value != '+∞'){
        return callback(new Error('请输入数字类型的区间值或+∞'));
      }
			callback();
		};
    var numberVal = (rule, value, callback) => {
      let reg = /^(-)?[0-9]+([.][0-9]{0,})?$/
			if (this.dislogRangeData.type == '1' && value && !value.match(reg) && value != '-∞') {
				return callback(new Error('请输入数字类型的区间值或-∞'));
			}
			callback();
		};
    
    let validateAge = (rule, value, callback) => {
      let reg = /^[1-9]\d*$/
      if (value && !value.match(reg)) {
        callback(new Error('请输入非零正整数'));
      } else {
        callback();
      }
    }
    return {
			companyOptions: [],
			sexOptions: [],
			phystageOptions: [],
			checked: [],
      tableTitle: '',
      relationList: [],
      // 表格数据
      tableTitle: '',
			editIndex: -1,
      // 表格数据
      // tableData: [],
			addAlias: false,
			dislogAliasData: {
				newAlias: '',
			},
			aliasRules: {
				newAlias: [
					{ required: true, message: '请输入别称', trigger: 'blur' },
				],
			},
			unicRules: {
				newUnic: [
					{ required: true, message: '请输入单位名称', trigger: 'blur' },
				],
			},
			addUnic: false,
			dislogUnicData: {
				newUnic: '',
				isdefault: true
			},
			addRange: false,
			dislogRangeData: {
				"age": "",
				"physicalExaminationOrgCode": "",
				"physicalExaminationOrgName": "",
				"physiologicalStaging": "",  // 生理分期字典id
				"referenceIntervalFirst": "",
				// referenceInterval: '',
				"referenceIntervalSecond": "",
				"sex": "",  //性别字典id
				// status: "1",  //状态 0、无效1、有效
				"type": "1", // 分类 1-按区间段，2-按内容
			},
			rangeRules: {
				age: [{ validator: validateAge, trigger: 'blur' }],
				sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
				physicalExaminationOrgCode: [{ required: true, message: '请选择体检机构', trigger: 'change' }],
				physiologicalStaging: [{ required: true, message: '请选择生理分期', trigger: 'change' }],
				physiologicalStaging: [{ required: true, message: '请选择生理分期', trigger: 'change' }],
				referenceIntervalFirst: [
          { required: true, message: '请输入参考区间', trigger: 'blur' },
          { validator: numberVal.bind(this), trigger: 'blur' }
        ],
				referenceIntervalSecond: [{ validator: checkInterval.bind(this), trigger: 'blur' }],
				// referenceInterval: [{ required: true, message: '请输入参考区间', trigger: 'blur' }],
			},
			dislogRangeTable: [],
			currentRow: {},
    }
  },
	created() {
		getCodeDictProject('peOrg').then( res => {
      this.companyOptions = res.data;
    });
		getCodeDictProject('sex').then( res => {
			this.sexOptions = res.data;
		});
		// 生理分期
		getCodeDictProject('phystage').then( res => {
			this.phystageOptions = res.data;
		});
	},
  activated(){
    this.$refs.examProjectLibrary.currentId = null
    this.$refs.examProjectLibrary.filterText = ''
    this.$refs.examProjectLibrary.getProjectLibraryList();
  },
	watch: {
		'dislogRangeData.physicalExaminationOrgCode': {
			handler(val) {
				if(val !== '') {
					let index = this.companyOptions.findIndex(item => val === item.id);
					if(index > -1 && (this.companyOptions[index].dictValue)){
						this.dislogRangeData.physicalExaminationOrgName = this.companyOptions[index].dictValue;
					}
				}
			}
			
		}
	},
  methods: {
		show() {
			this.$store.dispatch('loading/CHANGE_LOADING', true);
		},
		cancle() {
			this.$store.dispatch('loading/CHANGE_LOADING', false)
		},
		queryTableData(id, title, isLock, currentRow) {
      this.currentRow = currentRow
			this.show();
      this.tableTitle = title;
      this.relationList = []
      getProjectInfo({ ausPhysicalExaminatioItemId: id }).then( res => {
        this.relationList = res.data || []
				this.cancle();
      }).catch(err => {
				this.cancle();
			})
    },
    // 英文缩写校验
    inputChange(el,row,field){
      let val = el.replace(/[^a-zA-Z\-\_]/g,"")
      this.$set(row,field,val)
    },
		savePage() {
			this.show();
			saveReferenceIntervalInfo(this.relationList).then(res => {
				this.cancle();
				if (res.resultCode == constant.SUCCESS) {
          this.$message.success('保存成功')
				}
			}).catch(err => {
				this.cancle();
			})
		},
		addNewAlias(index) {
			this.editIndex = index;
			this.dislogAliasData.newAlias = '';
			this.addAlias = true;
		},
		saveAlias() {
			this.$refs['dislogAliasData'].validate((valid) => {
				if (valid) {
					let obj = {
						anotherName: this.dislogAliasData.newAlias,
						// status: '1', // 状态1、有效 0、无效
					}
					if(!this.relationList[this.editIndex].anotherConfigList) {
						this.$set(this.relationList[this.editIndex], 'anotherConfigList',[] )
					}
					this.relationList[this.editIndex].anotherConfigList.push(obj);
					this.editIndex = -1;
					this.addAlias = false;
				}
			});
		},
		delTag(arr, index) {
			arr.splice(index, 1);
		},
		addNewUnic(index) {
      this.dislogUnicData.newUnic = ''
			this.addUnic = true;
			this.editIndex = index;
		},
		saveUnic() {
			this.$refs['dislogUnicData'].validate((valid) => {
				if(valid) {
					let obj = {
						unit: this.dislogUnicData.newUnic,
						isdefault: this.dislogUnicData.isdefault ? '1' : '0',
						// status: '1',  // 状态 0、无效1、有效
					}
					if(!this.relationList[this.editIndex].unitConfigList) {
						this.$set(this.relationList[this.editIndex], 'unitConfigList',[] )
					}
					if(this.dislogUnicData.isdefault) {
						this.relationList[this.editIndex].unitConfigList.forEach(item => {
							item.isdefault = '0';
						})
					}
					this.relationList[this.editIndex].unitConfigList.push(obj);
					this.editIndex = -1;
					this.addUnic = false;
				}
			});
		},
		addNewRange(index) {
			this.editIndex = index;
      this.rangeClose()
			this.addRange = true;
			if(!this.relationList[index].intervalConfigList) {
				this.$set(this.relationList[this.editIndex], 'intervalConfigList',[] )
			}
			this.dislogRangeTable = constant.deepClone(this.relationList[index].intervalConfigList);			// this.dislogRangeTable.forEach(item => {
			// 	item.extractionId = this.relationList[index].id;
			// })
		},
		saveRange() {
			this.$set(this.relationList[this.editIndex], 'intervalConfigList',this.dislogRangeTable)
			// this.relationList[this.editIndex].intervalConfigList = this.dislogRangeTable;
			this.addRange = false;
			this.dislogRangeTable = [];
			// this.editIndex = index;
			// console.log(this.dislogRangeTable)
			// this.show()
			// saveReferenceIntervalInfo(this.dislogRangeTable).then( res => {
			// 	console.log(res)
			// 	this.cancle();
      // }).catch(err => {
			// 	this.cancle();
			// })
		},
		changeRangeType(val) {
				this.dislogRangeData.referenceInterval = '';
				this.dislogRangeData.referenceIntervalFirst = '';
				this.dislogRangeData.referenceIntervalSecond = '';
		},
    rangeClose(){
      this.dislogRangeData = {
        "age": "",
				"physicalExaminationOrgCode": "",
				"physicalExaminationOrgName": "",
				"physiologicalStaging": "",  // 生理分期字典id
				"referenceIntervalFirst": "",
				// referenceInterval: '',
				"referenceIntervalSecond": "",
				"sex": "",  //性别字典id
				// status: "1",  //状态 0、无效1、有效
				"type": "1", // 分类 1-按区间段，2-按内容
      }
    },
		addRangeItem() {
			
			this.$refs['dislogRange'].validate((valid) => {
				if(valid) {
					let obj = constant.deepClone(this.dislogRangeData);
          if(this.dislogRangeTable.length && obj.type != this.dislogRangeTable[0].type){
            this.$message.warning('请添加相同分类的数据')
            return
          }

					// 接口就这样，组装数据吧
					if(obj.type == '2') {
						// obj.referenceIntervalFirst = obj.referenceInterval;
						// obj.referenceIntervalSecond = obj.referenceInterval;
						obj.referenceIntervalSecond = obj.referenceIntervalFirst;
					}
					// if(obj.referenceIntervalSecond.trim() == '')
					// delete obj.referenceInterval;
					// obj.extractionId = this.relationList[this.editIndex].id
					this.dislogRangeTable.push(obj);
          this.rangeClose()
          this.$refs['dislogRange'].resetFields()
				}
			});
			
		},
		delRangeItem(i) {
			this.dislogRangeTable.splice(i, 1);
		}
  }
}

</script>

<style lang="less" scoped>
	// * {
	// 	margin: 0;
	// 	padding: 0;
	// }
	.top_box {
		height: 50px;
		line-height: 50px;
		border-bottom: 1px solid rgb(241, 238, 238);
	}

	.top_box h1 {
		font-weight: 600;
		margin-left: 15px;
	}
	/* 右侧表格 */
	.rightBox {
		flex: 1;
		// border: 1px solid #e3dddd;
		overflow-x: hidden;
		.right-top {
			background-color:#f1eeee;
			height: 50px;
			line-height: 50px;
			font-size: 14px;
			font-weight: 700;
			span{
				border-left: 4px solid #0a66e6;
				padding-left: 20px;
			}
		}
	}
  .right-title{
    background: #f8f8f8;
    padding: 10px 25px;
    margin-left: 15px;
    position: relative;
  }
  .right-title::before{
    content: '';
    position: absolute;
    top: 11px;
    left: 15px;
    width: 3px;
    height: 18px;
    background: #f76767;
  }

	.rightBox /deep/ .el-table .col-reset .cell {
		display: flex;
		justify-content: center;
		flex-wrap: wrap;
		align-content: center;	
	}
	.btn {
		width: 15px;
		height: 15px;
		padding: 0px;
	}
  .synonym-item{
    max-width: 166px;
    white-space: break-spaces;
    height: fit-content;
    padding: 0px 8px;
    margin: 2px 8px 2px 0;
    background: #f5f5f5;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
  }
	/deep/ i.el-icon-plus{
		font-size: 12px !important;
	}
	
	/deep/ .el-button--text:focus, .el-button--text:hover {
		color: #66b1ff !important;
	}
	/deep/ .el-dialog__body .el-input__inner {
    background: #fff !important;
	}
	.Defaultbutton {
		padding: 7px 15px;
	}
	/deep/ .el-table__empty-block {
  width: 100% !important;
}
</style>